import { Eyes, registerEyeCapModifier } from '$lib/eyes';
import { log } from '$lib/log';
import { registerOnTick } from '$lib/clock';
import { Types, addComponent, defineComponent, defineQuery, hasComponent, removeComponent } from '$lib/ecs';

/**
 * Blinded by a bright flash of light, removed gradually
 */
export const FlashBlinded = defineComponent('FlashBlinded', {
  allowRange: Types.ui16,
  delay: Types.ui16,
});

const flashBlindedQuery = defineQuery([FlashBlinded]);

export const addFlashBlind = (world, e, delay) => {
  if (hasComponent(world, FlashBlinded, e)) {
    FlashBlinded.delay[e] += delay;
  } else {
    addComponent(world, FlashBlinded, e);
    FlashBlinded.delay[e] = delay;
  }
  log(`Delay: ${delay}`);
  FlashBlinded.allowRange[e] = 0;
};

registerEyeCapModifier(FlashBlinded, (world, e) => {
  return FlashBlinded.allowRange[e];
});

registerOnTick((world) => {
  for (let e of flashBlindedQuery(world)) {
    log('flash tick');
    if (FlashBlinded.delay[e] > 0) {
      --FlashBlinded.delay[e];
    } else {
      ++FlashBlinded.allowRange[e];
      if (FlashBlinded.allowRange[e] >= Eyes.range[e]) {
        removeComponent(world, FlashBlinded, e);
      }
    }
  }
  return world;
});
